//
//  ZDComposeViewController.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/11/5.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDComposeViewController.h"
#import "ZDUserAccount.h"
#import <Masonry/Masonry.h>
#import "UIBarButtonItem+Extension.h"
#import "ZDTextView.h"
#import "ZDEmojiViewController.h"
#import "UITextView+Extension.h"
#import "ZDNetworkTool.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "ZDPhotoSelectorViewController.h"

//发微博最大字数限制
#define ZDMaxWordNumber 20

@interface ZDComposeViewController ()

@property (nonatomic, strong) ZDTextView *textView;

@property (nonatomic, strong) UIToolbar *toolBar;

///记录toolBar的底部约束
@property (nonatomic, strong) NSLayoutConstraint *toolBarBottomC;

///表情控制器
@property (nonatomic, strong) ZDEmojiViewController *emojiVC;

///字数提示label
@property (nonatomic, strong) UILabel *wordTipLabel;

///图片选择器
@property (nonatomic, strong) ZDPhotoSelectorViewController *photoSelectorVC;

///记录图片选择器view的底部约束
@property (nonatomic, strong) NSLayoutConstraint *photoSelectorViewBottomC;

@end

@implementation ZDComposeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setNavigationBar];
    
    [self prepareUI];
    
    [self setTextView];
    
    [self setToolBar];
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self.textView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    
//    [self.textView becomeFirstResponder];
//}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.photoSelectorViewBottomC.constant != 0)
    {
        [self.textView becomeFirstResponder];
    }
}

//移除通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//通知回调方法
- (void)textDidChange
{
    self.navigationItem.rightBarButtonItem.enabled = self.textView.hasText;
    
    int count = ZDMaxWordNumber - (int)self.textView.emojiText.length;
    
    self.wordTipLabel.text = [NSString stringWithFormat:@"%d", count];
    
    self.wordTipLabel.textColor = count < 0 ? [UIColor redColor] : [UIColor blueColor];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notice
{
//    ZDLog(@"%@", notice);
    
    NSDictionary *dict = notice.userInfo;
    
    CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect endFrame = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat offsetY = -(ZDScreenSize.height - endFrame.origin.y);
    
    //更新toolBar的约束
    [_toolBar mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(44);
        make.bottom.mas_equalTo(self.view).offset(offsetY);
    }];
    
    [UIView animateWithDuration:duration animations:^{
        
        [self.view layoutIfNeeded];
    }];
}

//准备UI
- (void)prepareUI
{
    //添加子控件
    [self.view addSubview:self.textView];
    [self.view addSubview:self.photoSelectorVC.view];
    [self.view addSubview:self.toolBar];
    [self.view addSubview:self.wordTipLabel];
    
    
    //添加约束
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(_toolBar.mas_top);
    }];
    
    [_wordTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(_toolBar.mas_top).offset(-8);
        make.right.mas_equalTo(self.view.mas_right).offset(-8);
    }];
    
//    [_photoSelectorVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.left.right.mas_equalTo(self.view);
//        make.bottom.mas_equalTo(self.view.mas_bottom).offset(ZDScreenSize.height * 0.6);
//        make.height.mas_equalTo(ZDScreenSize.height * 0.6);
//    }];
    
    _photoSelectorVC.view.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[psvc]-0-|" options:0 metrics:nil views:@{@"psvc": _photoSelectorVC.view}]];
    
    self.photoSelectorViewBottomC = [NSLayoutConstraint constraintWithItem:_photoSelectorVC.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:ZDScreenSize.height * 0.6];
    
    [self.view addConstraint:self.photoSelectorViewBottomC];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_photoSelectorVC.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:ZDScreenSize.height * 0.6]];
}

//设置导航栏
- (void)setNavigationBar
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发微博" style:UIBarButtonItemStyleDone target:self action:@selector(sendStatus)];
    
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    [self setTitleView];
}

//设置中间titleView
- (void)setTitleView
{
    NSString *userName = [ZDUserAccount loadUserAccount].name;
    
    NSString *text = [NSString stringWithFormat:@"发微博\n%@", userName];
    
    //创建属性文本
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    NSRange range = [text rangeOfString:userName];
    
    //设置属性
    NSDictionary *attributeDict = @{
                                    NSFontAttributeName: [UIFont systemFontOfSize:15],
                                    NSForegroundColorAttributeName: [UIColor lightGrayColor]
                                    };
    
    [attributeStr addAttributes:attributeDict range:range];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    
    //设置多行
    titleLabel.numberOfLines = 0;
    //设置文本居中
    titleLabel.textAlignment = NSTextAlignmentCenter;
    //赋值label的属性文本
    titleLabel.attributedText = attributeStr;
    
    [titleLabel sizeToFit];
    
    self.navigationItem.titleView = titleLabel;
}

//取消
- (void)cancel
{
    [self.textView resignFirstResponder];
    
    [SVProgressHUD dismiss];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//发微博
- (void)sendStatus
{
    //取出textView的文本
    NSString *text = [self.textView emojiText];
    
    //取出发表微博的配图
    UIImage *image = self.photoSelectorVC.photos.firstObject;
    
    
    if (self.wordTipLabel.text.intValue < 0)
    {
        [SVProgressHUD showInfoWithStatus:@"超出微博内容长度" maskType:SVProgressHUDMaskTypeBlack];
        
        return;
    }
    
    [SVProgressHUD showWithStatus:@"正在发送微博..." maskType:SVProgressHUDMaskTypeBlack];
    
    //发微博
    [[ZDNetworkTool sharedInstance] sendStatus:text image:image access_token:[ZDUserAccount loadUserAccount].access_token success:^(id responseObject) {
        
        [SVProgressHUD showSuccessWithStatus:@"微博发送成功..." maskType:SVProgressHUDMaskTypeBlack];
        
        [self cancel];
        
//        ZDLog(@"responseObject:%@", responseObject);
        
    } failure:^(NSError *error) {
        
        if (error)
        {
            [SVProgressHUD showErrorWithStatus:@"发送微博失败..." maskType:SVProgressHUDMaskTypeBlack];
            
            ZDLog(@"发送微博失败:%@", error);
        }
    }];
}


//设置textView
- (void)setTextView
{
    //设置占位文本
    self.textView.placeholder = @"分享新鲜事...";
}


//设置toolBar
- (void)setToolBar
{
    NSMutableArray *items = [NSMutableArray array];
    
    NSArray *itemSettings = @[
                @{@"imageName" : @"compose_toolbar_picture", @"action" : @"picture"},
                @{@"imageName" : @"compose_trendbutton_background", @"action" : @"trend"},
                @{@"imageName" : @"compose_mentionbutton_background", @"action" : @"mention"},
                @{@"imageName" : @"compose_emoticonbutton_background", @"action" : @"emoticon"},
                @{@"imageName" : @"compose_addbutton_background", @"action" : @"add"}];
    
    for (NSDictionary *dict in itemSettings)
    {
        UIBarButtonItem *item = [UIBarButtonItem barButtonItemWith:dict[@"imageName"]];
        
        UIButton *btn = item.customView;
        
        //将字符串转换为方法名
        SEL selector = NSSelectorFromString(dict[@"action"]);
    
        //为按钮添加事件
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
        
        [items addObject:item];
        
        //添加弹簧
        [items addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]];
    }
    
    //移除最后一个弹簧
    [items removeLastObject];
    
    self.toolBar.items = items;
}


#pragma mark - barButtonItem回调方法
- (void)picture
{
    //退出键盘
    [self.textView resignFirstResponder];
    
    self.photoSelectorViewBottomC.constant = 0;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.view layoutIfNeeded];
    }];
}

- (void)trend
{
    ZDLog(@"%s", __func__);
}

- (void)mention
{
    ZDLog(@"%s", __func__);
}

///键盘切换
- (void)emoticon
{
    //退出键盘
    [self.textView resignFirstResponder];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //inputView为nil，则会呼出系统键盘
        self.textView.inputView = self.textView.inputView ? nil : self.emojiVC.view;
        
        //呼出键盘
        [self.textView becomeFirstResponder];
    });
}

- (void)add
{
    ZDLog(@"%s", __func__);
}



#pragma mark 懒加载
- (UIToolbar *)toolBar
{
    if (!_toolBar)
    {
        _toolBar = [[UIToolbar alloc] init];
        
        _toolBar.barTintColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    }
    
    return _toolBar;
}

- (ZDTextView *)textView
{
    if (!_textView)
    {
        _textView = [[ZDTextView alloc] init];
        
        _textView.backgroundColor = [UIColor clearColor];
        
        _textView.font = [UIFont systemFontOfSize:18];
        
        //允许垂直方向有弹簧效果
        _textView.alwaysBounceVertical = YES;
        
        //设置拖拽时隐藏键盘
        _textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    
    return _textView;
}

- (ZDEmojiViewController *)emojiVC
{
    if (!_emojiVC)
    {
        _emojiVC = [[ZDEmojiViewController alloc] init];
        
        _emojiVC.textView = self.textView;
    }
    
    return _emojiVC;
}

- (UILabel *)wordTipLabel
{
    if (!_wordTipLabel)
    {
        _wordTipLabel = [[UILabel alloc] init];
        
        _wordTipLabel.textColor = [UIColor blueColor];
        
        _wordTipLabel.text = [NSString stringWithFormat:@"%d", ZDMaxWordNumber];
    }
    
    return _wordTipLabel;
}

- (ZDPhotoSelectorViewController *)photoSelectorVC
{
    if (!_photoSelectorVC)
    {
        _photoSelectorVC = [[ZDPhotoSelectorViewController alloc] init];
        
        [self addChildViewController:_photoSelectorVC];
    }
    
    return _photoSelectorVC;
}

@end
